package com.situ.mall.controller;

import com.situ.mall.util.ImageServerUtil;
import com.situ.mall.util.JSONResult;
import com.situ.mall.util.QiniuUtils;
import com.situ.mall.util.RedisConstant;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;

    // SpringMVC把上传的信息封装到MultipartFile
    @RequestMapping("/uploadImage")
    @ResponseBody
    public JSONResult uploadImage(MultipartFile file) {
        // 返回图片的名字 a.png
        String fileName = file.getOriginalFilename();
        // png
        String extension = FilenameUtils.getExtension(fileName);
        String uuidName = UUID.randomUUID().toString();
        // 0a410ad6580c454da8016ded49949031.png
        String newFileName = uuidName + "." + extension;

        if (ImageServerUtil.IMG_SERVER == ImageServerUtil.LOCAL) {
            String filePath = "D:\\mypic\\" + newFileName;
            try {
                file.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (ImageServerUtil.IMG_SERVER == ImageServerUtil.QINIU) {
            try {
                QiniuUtils.upload2Qiniu(file.getBytes(), newFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 将上传的图片保存到Redis中
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE, newFileName);
        System.out.println("上传图片：" + newFileName);

        return JSONResult.ok("上传成功", newFileName);
    }

    public static void main(String[] args) {
        String name = UUID.randomUUID().toString();
        // 0a410ad6-580c-454d-a801-6ded49949031
        System.out.println(name);
        // 0a410ad6580c454da8016ded49949031
        System.out.println(name.replace("-", ""));
    }
}
